package goodbaby.dklt.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.classic.core.activity.BaseActivity;
import com.classic.core.utils.DateUtil;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;
import com.tgd.gbb.uikit.ui.dialog.WLQQTimePicker;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import goodbaby.dklt.GbbApplication;
import goodbaby.dklt.GbbPreferences;
import goodbaby.dklt.R;
import goodbaby.dklt.adapter.AttendanceAdapter;
import goodbaby.dklt.adapter.CommonAdapter;
import goodbaby.dklt.adapter.ViewHolder;
import goodbaby.dklt.bean.AttendanceBean;
import goodbaby.dklt.bean.AttendanceClassBean;
import goodbaby.dklt.bean.AttendanceSchoolBean;
import goodbaby.dklt.bean.ChildrenBean;
import goodbaby.dklt.bean.ClassBean;
import goodbaby.dklt.bean.ClassListInfo;
import goodbaby.dklt.customerview.AttendancePieChart;
import goodbaby.dklt.fragment.ClassFragment;
import goodbaby.dklt.fragment.ClassGridFragment;
import goodbaby.dklt.fragment.StudyFragment;

/**
 * Created by Jayden on 2016/4/24 16:44.
 *
 * @version V1.0
 * @Title: AttendanceActivity
 * @Description: 考勤页面/请假页面
 */
public class AttendanceActivity extends BaseActivity {

    private CommonAdapter adapter;
    private Button btnFind;
    private String endCurrentDate;
    private String endDate;
    private ImageView ivBack;
    private LinearLayout llListAttendance;
    private ListView lvAttendance;
    private RelativeLayout rlEndTime;
    private RelativeLayout rlStartTime;
    private String startCurrentDate;
    private String startDate;
    private PopupWindow timePopupWindow;
    private TextView tvEndTime;
    private TextView tvHistory;
    private TextView tvStartTime;
    private TextView tvTitle;
    private TextView tvLimit;
    private int type = 0;

    private LinearLayout llClassChoice;
    private LinearLayout llNameChoice;
    private TextView tvClassChoice;
    private TextView tvNameChoice;

    private TextView tvAttendance;
    private TextView tvLeave;
    private TextView tvOther;

    private List<ClassListInfo> mClassList;
    private List<ChildrenBean> mChildrenList;

    private ClassListInfo mChoiceClass;
    private ChildrenBean mChoiceChildren;

    private PopupWindow mClassListPopupWindow;
    private PopupWindow mChildrenListPopupWindow;
    private ListView classListView;
    private ListView mChildrenListView;

    private AttendancePieChart apcPieChart;

    private void getAttendanceData() {
        if (mChoiceChildren == null) {
            ToastUtil.showToast(this, "姓名不能为空");
            return;
        }

        if (StringUtil.isEmpty(startCurrentDate)) {
            ToastUtil.showToast(this, "开始时间不能为空");
            return;
        }
        if (StringUtil.isEmpty(endCurrentDate)) {
            ToastUtil.showToast(this, "结束时间不能为空");
            return;
        }
        long l1 = Long.parseLong(DateUtil.getTime(startCurrentDate));
        long l2 = Long.parseLong(DateUtil.getTime(endCurrentDate));
        if (l2 - l1 > 2592000000L) {
            ToastUtil.showToast(this, "选择时间不能超过30天");
            return;
        }
        if (l1 > l2) {
            ToastUtil.showToast(this, "开始时间不能大于结束时间");
            return;
        }
        ActionHelp.queryAttendanceList(this, DateUtil.getTime(startCurrentDate), DateUtil.getTime(endCurrentDate), mChoiceChildren.getId(), new ObjectCallback<List<AttendanceBean>>() {
            @Override
            public void onError(int code) {
                ToastUtil.showToast(AttendanceActivity.this, "查询失败" + code);
            }

            @Override
            public void onSuccess(List<AttendanceBean> response) {
                // adapter = new AttendanceAdapter(AttendanceActivity.this, response);
                adapter = new CommonAdapter<AttendanceBean>(AttendanceActivity.this, R.layout.item_attendance, response) {

                    @Override
                    public void convert(ViewHolder helper, AttendanceBean item, int position) {
                        helper.setText(R.id.item_tv_date, item.getCreatedOn());
                        helper.setText(R.id.item_tv_enter_time, item.getOneCreateOn_Time());
                        helper.setText(R.id.item_tv_leave_time, item.getTwoCreateOn_Time());

                        TextView tvWeek = helper.getView(R.id.item_tv_week);
                        tvWeek.setVisibility(View.GONE);
                    }
                };
                lvAttendance.setAdapter(adapter);
                llListAttendance.setVisibility(View.VISIBLE);
            }

            @Override
            public Type getType() {
                return new TypeToken<List<AttendanceBean>>() {
                }.getType();
            }
        });
    }

    public void TimeDialog(View paramView) {
        LayoutInflater mLayoutInflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);

        //right_pop為泡泡的布局
        View view = mLayoutInflater.inflate(R.layout.date_popupwindows, null);
        WLQQTimePicker localWLQQTimePicker = (WLQQTimePicker) view.findViewById(R.id.timepicker);
        localWLQQTimePicker.setDate(new Date().getTime());
        localWLQQTimePicker.init(new MyCallBack());
        timePopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        timePopupWindow.setFocusable(true);
        timePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        timePopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        timePopupWindow.setOutsideTouchable(true);
        timePopupWindow.showAsDropDown(paramView);
    }

    public int getLayoutResId() {
        return R.layout.activity_attendance;
    }

    public void initData() {
        super.initData();
    }

    public void initView() {
        super.initView();
        tvTitle = (TextView) findViewById(R.id.tv_common_title);
        ivBack = (ImageView) findViewById(R.id.iv_common_back);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        tvHistory = (TextView) findViewById(R.id.tv_common_leave_history);
        tvHistory.setText("请假记录");
        tvHistory.setOnClickListener(this);
        btnFind = (Button) findViewById(R.id.btn_find);
        btnFind.setOnClickListener(this);
        llListAttendance = (LinearLayout) findViewById(R.id.ll_attendance_list);
        lvAttendance = (ListView) findViewById(R.id.lv_attendance);
        rlStartTime = (RelativeLayout) findViewById(R.id.rl_start_time);
        rlStartTime.setOnClickListener(this);
        rlEndTime = (RelativeLayout) findViewById(R.id.rl_end_time);
        rlEndTime.setOnClickListener(this);
        tvStartTime = (TextView) findViewById(R.id.tv_start_time);
        tvEndTime = (TextView) findViewById(R.id.tv_end_time);
        tvLimit = (TextView) findViewById(R.id.tv_limit);

        tvClassChoice = (TextView) findViewById(R.id.tv_class_choice);
        tvNameChoice = (TextView) findViewById(R.id.tv_name_choice);
        llClassChoice = (LinearLayout) findViewById(R.id.ll_class_choice);
        llNameChoice = (LinearLayout) findViewById(R.id.ll_name_choice);
        llClassChoice.setOnClickListener(this);
        llNameChoice.setOnClickListener(this);

        apcPieChart = (AttendancePieChart) findViewById(R.id.apc_pie_chart);
        tvAttendance = (TextView) findViewById(R.id.tv_attendace);
        tvLeave = (TextView) findViewById(R.id.tv_leave);
        tvOther = (TextView) findViewById(R.id.tv_other);


        tvTitle.setText("考勤");
        tvHistory.setVisibility(View.GONE);
        btnFind.setText("查询");
        llListAttendance.setVisibility(View.GONE);

        loadData();
    }

    private void loadData() {
        //判断是否是园长
        String role = GbbPreferences.getRole();
        if ("2".equals(role)) {
            //园长
            toLoadClassList();

            showSchoolAttendance(GbbApplication.getAttendanceSchoolBean());
        } else {
            //老师
            mChoiceClass = new ClassListInfo(GbbPreferences.getClassName(), Integer.parseInt(GbbPreferences.getClassId()));
            tvClassChoice.setText(mChoiceClass.getNAME());
            llClassChoice.setClickable(false);
            toLoadChildrenList(mChoiceClass.getID());

            showClassAttendance(GbbApplication.getAttendanceClassBean());
        }
    }

    public void showSchoolAttendance(AttendanceSchoolBean bean) {

        apcPieChart.setValues(bean.getAttendanceCount(), bean.getLevelCount(), bean.getChildrenCount() - bean.getAttendanceCount());

        tvAttendance.setText("实到" + bean.getAttendanceCount() + "人");
        tvLeave.setText("请假" + bean.getLevelCount() + "人");
        tvOther.setText("未到" + (bean.getChildrenCount() - bean.getAttendanceCount()) + "人");

    }

    public void showClassAttendance(AttendanceClassBean bean) {

        apcPieChart.setValues(bean.getAttendanceCount(), bean.getLevelCount(), bean.getChildrenCount() - bean.getAttendanceCount());

        tvAttendance.setText("实到" + bean.getAttendanceCount() + "人");
        tvLeave.setText("请假" + bean.getLevelCount() + "人");
        tvOther.setText("未到" + (bean.getChildrenCount() - bean.getAttendanceCount()) + "人");
    }

    private void toLoadClassList() {
        ActionHelp.getClassList(activity, new ObjectCallback<List<ClassListInfo>>() {

            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(AttendanceActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "失败:" + code);
                }
            }

            @Override
            public void onError(int code, String errorMessage) {
                super.onError(code, errorMessage);
                ToastUtil.showToast(activity, "失败");
            }

            @Override
            public void onHttpError(int statusCode) {
                super.onHttpError(statusCode);
                ToastUtil.showToast(activity, "失败");
            }

            public void onSuccess(List<ClassListInfo> paramAnonymousList) {
                mClassList = paramAnonymousList;
                mChoiceClass = paramAnonymousList.get(0);
                tvClassChoice.setText(mChoiceClass.getNAME());

                toLoadChildrenList(mChoiceClass.getID());
            }

            @Override
            public Type getType() {
                return new TypeToken<List<ClassListInfo>>() {
                }.getType();
            }
        });
    }

    private void toLoadChildrenList(int classId) {
        ActionHelp.gbbAttendanceClass(activity, classId + "", new ObjectCallback<AttendanceClassBean>() {
            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(AttendanceActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "失败:" + code);
                }
            }

            @Override
            public void onError(int code, String errorMessage) {
                super.onError(code, errorMessage);
                ToastUtil.showToast(activity, "失败");
            }

            @Override
            public void onHttpError(int statusCode) {
                super.onHttpError(statusCode);
                ToastUtil.showToast(activity, "失败");
            }

            @Override
            public void onSuccess(AttendanceClassBean response) {

                mChildrenList = response.getClasschildrenlist();
                mChoiceChildren = mChildrenList.get(0);
                tvNameChoice.setText(mChoiceChildren.getName());

            }

            @Override
            public Type getType() {
                return new TypeToken<AttendanceClassBean>() {
                }.getType();
            }
        });
    }

    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
    }

    protected void onDestroy() {
        super.onDestroy();
    }

    public void viewClick(View paramView) {
        super.viewClick(paramView);
        switch (paramView.getId()) {
            default:
                break;
            case R.id.iv_common_back:
                finish();
                break;
            case R.id.tv_common_leave_history:
                startActivity(new Intent(this, LeaveHistoryActivity.class));
                break;
            case R.id.btn_find:
                getAttendanceData();

                break;
            case R.id.rl_start_time:
                type = 0;
                TimeDialog(rlStartTime);
                break;
            case R.id.rl_end_time:
                type = 1;
                TimeDialog(rlEndTime);
                break;
            case R.id.ll_class_choice:
                showClassListPopu();
                break;
            case R.id.ll_name_choice:
                showChildrenListPopu();
                break;
        }

    }

    private void showClassListPopu() {
        if (mClassList == null) {
            return;
        }

        if (mClassListPopupWindow == null) {
            View contentView = View.inflate(this, R.layout.popu_class_list, null);
            mClassListPopupWindow = new PopupWindow(contentView,
                    llClassChoice.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);

            mClassListPopupWindow.setTouchable(true);
            mClassListPopupWindow.setOutsideTouchable(true);
            // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
            mClassListPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            classListView = (ListView) contentView.findViewById(R.id.lv_listview);
            mClassListPopupWindow.setContentView(contentView);

            classListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mChoiceClass = ((ClassListAdapter) classListView.getAdapter()).getItem(position);
                    tvClassChoice.setText(mChoiceClass.getNAME());
                    dismissClassListPopu();

                    toLoadChildrenList(mChoiceClass.getID());
                }


            });
        }

        classListView.setAdapter(new ClassListAdapter(this, mClassList));
        mClassListPopupWindow.showAsDropDown(llClassChoice);
    }

    private void dismissClassListPopu() {
        if (mClassListPopupWindow != null && mClassListPopupWindow.isShowing()) {
            mClassListPopupWindow.dismiss();
        }
    }

    private void showChildrenListPopu() {
        if (mChildrenList == null) {
            return;
        }

        if (mChildrenListPopupWindow == null) {
            View contentView = View.inflate(this, R.layout.popu_class_list, null);
            mChildrenListPopupWindow = new PopupWindow(contentView,
                    llNameChoice.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);

            mChildrenListPopupWindow.setTouchable(true);
            mChildrenListPopupWindow.setOutsideTouchable(true);
            // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
            mChildrenListPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            mChildrenListView = (ListView) contentView.findViewById(R.id.lv_listview);
            mChildrenListPopupWindow.setContentView(contentView);

            mChildrenListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mChoiceChildren = ((ChildrenListAdapter) mChildrenListView.getAdapter()).getItem(position);
                    tvNameChoice.setText(mChoiceChildren.getName());
                    dismissChildrenListPopu();
                }
            });
        }

        mChildrenListView.setAdapter(new ChildrenListAdapter(this, mChildrenList));
        mChildrenListPopupWindow.showAsDropDown(llNameChoice);
    }

    private void dismissChildrenListPopu() {
        if (mChildrenListPopupWindow != null && mChildrenListPopupWindow.isShowing()) {
            mChildrenListPopupWindow.dismiss();
        }
    }

    public class MyCallBack
            implements WLQQTimePicker.CallBack {
        public MyCallBack() {
        }

        public void Cancel() {
            timePopupWindow.dismiss();
        }

        public void ConfirmAndGetData(String paramString) {
            if (type == 0) {
                tvStartTime.setText(paramString);
                startDate = paramString;
                startCurrentDate = paramString + ":00";
            } else {
                AttendanceActivity.this.tvEndTime.setText(paramString);
                endDate = paramString;
                endCurrentDate = paramString + ":00";
            }
            timePopupWindow.dismiss();

        }
    }

    private class ClassListAdapter extends CommonAdapter<ClassListInfo> {

        public ClassListAdapter(Context context, List<ClassListInfo> mDatas) {
            super(context, R.layout.item_list_class_name_list, mDatas);
        }

        @Override
        public void convert(ViewHolder helper, ClassListInfo item, int position) {
            helper.setText(R.id.tv_class_name, item.getNAME());
        }
    }

    private class ChildrenListAdapter extends CommonAdapter<ChildrenBean> {

        public ChildrenListAdapter(Context context, List<ChildrenBean> mDatas) {
            super(context, R.layout.item_list_class_name_list, mDatas);
        }

        @Override
        public void convert(ViewHolder helper, ChildrenBean item, int position) {
            helper.setText(R.id.tv_class_name, item.getName());
        }
    }
}
